﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PJB.FacetedNavigation;
using PJBWebsite.Objects;

namespace PJBWebsite
{
    public partial class Results : System.Web.UI.Page
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            grdList.ItemDataBound += grdList_ItemDataBound;
            TextSearchControl1.Search += TextSearchControl1_Search;
            PagingControl1.RecordsPerPageChanged += PagingControl1_RecordsPerPageChanged;
            this.Populate();

            var url = new ListingQuery(this.Request.Url.PathAndQuery);
            url.DimensionValueList.Clear();
            url.FieldFilters.Clear();
            url.FieldSorts.Clear();
            url.Keyword = null;
            url.NonParsedFieldList.Clear();
            lblReset.Text = "<a class=\"r\" id=\"facetclearall\" href=\"" + url.ToString() + "\" title=\"Clear all filters\" rel=\"nofollow\">reset</a>";
        }

        private void PagingControl1_RecordsPerPageChanged(object sender, EventArgs e)
        {
            var url = new PagingURL(this.Request.Url.AbsoluteUri);
            url.RecordsPerPage = PagingControl1.RecordsPerPage;
            url.PageOffset = 1;
            this.Response.Redirect(url.ToString());
        }

        private void TextSearchControl1_Search(object sender, EventArgs e)
        {
            var url = new PagingURL(this.Request.Url.PathAndQuery);
            url.Text = TextSearchControl1.SearchText;
            this.Response.Redirect(url.ToString());
        }

        private void Populate()
        {
            using (var factory = RepositoryConnection.GetFactory())
            {
                var service = factory.CreateChannel();
                var query = new ListingQuery(this.Request.Url.PathAndQuery);
                var results = RepositoryConnection.QueryData(query, service);
                grdList.DataSource = results.RecordList;
                grdList.DataBind();
                PagingControl1.ItemCount = results.TotalRecordCount;

                ResultsFilterDisplayControl1.Populate(results, query);
                DimensionListControl1.Populate(results);
            }
        }

        private void grdList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var dataItem = e.Item.DataItem as ListingItem;
                var ctrl = e.Item.FindControl("ListingItemControl1") as PJBWebsite.UserControls.ListingItemControl;
                ctrl.Populate(dataItem);
            }
        }

    }
}